package io.bloom.site.service;

import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.Lang;
import org.nutz.lang.Times;
import org.nutz.lang.util.Context;
import org.nutz.mvc.Loading;
import org.nutz.mvc.Mvcs;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Activity
 *
 * @author T_T
 * @since 9/21/15
 */
@IocBean(name = "uploadService",create = "init")
public class UploadService {

    private String uploadLocalDir;

    private String storeDir = "upload";

    public void init() {
        javax.servlet.ServletContext servletContext = Mvcs.getServletContext();
        Object attribute = servletContext.getAttribute(Loading.CONTEXT_NAME);
        if (attribute == null) {
            throw new RuntimeException("init fail");
        }

        Context context=(Context)attribute;
        uploadLocalDir = context.get("app.root") + File.separator + storeDir;
    }


    public String move(File file) throws IOException {
        if (file == null || !file.exists()) {
            throw new IllegalArgumentException("file not  exists,so can not move");
        }

        String filePathInDir=buildFileNameInDir(file);
        Files.move(file, buildLocalFullPath(filePathInDir));

        return storeDir+File.separator+filePathInDir;
    }


    /**
     * 构建本地文件
     * @param fileNameInDir 在文件夹相对位置的名字 /home/admin/aa/upload/"151212fileName.txt"
     * @return 在文件夹相对位置的名字
     */
    public File buildLocalFullPath(String fileNameInDir) {
        String filePath = uploadLocalDir + File.separator + fileNameInDir;
        return new File(filePath);
    }


    /**
     * 创建在文件夹内的路径
     * @param file 文件
     * @return 151212fileName.txt
     */
    public String buildFileNameInDir(File file){
        String fileName = Lang.digest("MD5",file);
        String suffixName = Files.getSuffixName(file.getName());
        String date = Times.format("yyMMdd", new Date());
        return date + File.separator + fileName +"."+ suffixName;
    }
}
